package com.crazydream.wechat.system.controller;

import java.util.Iterator;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.crazydream.wechat.system.model.Resource;
import com.crazydream.wechat.system.model.Role;
import com.crazydream.wechat.system.model.User;

@Controller
public class IndexController {

	/**
	 * 跳转到登录页面
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/login")
	public String login(Model model) {
		return "login";
	}
	
	@RequestMapping(value = "/signOnSuccess")
	public String signOnSuccess(Model model) {
		return "redirect:/index";
	}

	/**
	 * 跳转到注册页面
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/register")
	public String register(Model model) {
		return "register";
	}

	/**
	 * 首页
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/index")
	public String index(Model model) {

		Object principal = SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();
		if (principal instanceof UserDetails) {
			User user = (User) ((UserDetails) principal);
			model.addAttribute("user", user);
			for (Role role : user.getRoleList()) {
				Iterator<Resource> i = role.getResourceList().iterator();
				while (i.hasNext()) {
					Resource r = i.next();
					System.out.println(r.getDescr());
				}
			}
			return "index";
		} else {
			return "login";
		}
	}
}
